package com.huanke.iot.gateway.io;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.google.common.collect.Maps;
import com.huanke.iot.gateway.onlinecheck.OnlineCheckService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

/**
 * @author haoshijing
 * @version 2018年04月02日 15:17
 **/
@Slf4j
public abstract  class AbstractHandler {

    private static  ConcurrentMap<String,AbstractHandler> handlerMap= Maps.newConcurrentMap();
    @Autowired
    private OnlineCheckService onlineCheckService;
    @PostConstruct
    public void init(){
        handlerMap.putIfAbsent(getTopicType(),this);
    }
    protected abstract String getTopicType();


    public  void  handler(String topic, byte[] payloads){
    	//host
        Integer id = getDeviceIdFromTopic(topic);
        onlineCheckService.resetOnline(id);
        //child
	    String childId = null;
	    try {
		    JSONObject jsonObject = JSON.parseObject(new String(payloads));
		    childId = getChildId(jsonObject);
	    } catch (Exception e) {
		    log.error("获取childId失败={}", e);
	    }
	    if (childId != null){
		    onlineCheckService.resetChildOnline(id,childId);
	    }
        doHandler(topic,payloads);

    }
    public abstract void  doHandler(String topic, byte[] payloads);

    public static AbstractHandler getHandler(String topic){
        String type = getTypeFromTopic(topic);
        return handlerMap.get(type);
    }

    protected Integer getDeviceIdFromTopic(String topic){
        int idx = topic.lastIndexOf("/");
        Integer deviceId =  Integer.valueOf(topic.substring(idx+1));
        return deviceId;
    }
    private static String getTypeFromTopic(String topic){
        int idx = topic.lastIndexOf("/");
        String dataStr = topic.substring(0,idx);
        idx = dataStr.lastIndexOf("/");
        return dataStr.substring(idx+1);
    }

	public static String getChildId(Object object) throws Exception{

		if(object instanceof JSONObject) {
			JSONObject jsonObject = (JSONObject) object;
			for (Map.Entry<String, Object> entry: jsonObject.entrySet()) {
				Object o = entry.getValue();
				if(o instanceof String) {
					String childId = o.toString();
					if (!StringUtils.isEmpty(entry.getKey()) && "childid".equals(entry.getKey()) && !StringUtils.isEmpty(childId)){
						return childId;
					}
				} else {
					String childId = getChildId(o);
					if (childId != null){
						return  childId;
					}
				}
			}
		}
		if(object instanceof JSONArray) {
			JSONArray jsonArray = (JSONArray) object;
			for(int i = 0; i < jsonArray.size(); i ++) {
				String childId = getChildId(jsonArray.get(i));
				if (childId != null){
					return  childId;
				}
			}
		}
		return null;
	}

}
